<?php
namespace app\admin\controller;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Controller;

class Excel extends Controller {
    public function test($id=0){
        $naire=\app\common\model\Questionnaire::get($id);
        list($group,$base)=$naire->tongji($id);

        $spreadsheet=new Spreadsheet();
        $spreadsheet->setActiveSheetIndex(0);
        $sheet=$spreadsheet->getActiveSheet();

//        第一行
        $sheet->setCellValue('A1','')
            ->setCellValue('B1','');

        $column=range('A','Z');
        $tmp=range('A','Z');
        $tmp=array_map(function($v){
            return "A{$v}";
        },$tmp);
        $column=array_merge($column,$tmp);


        //设置列的初始位置
        $col=2;
        foreach($base as $i=>$t){
            $length=count($t['answer'],COUNT_RECURSIVE)-1;
            $sheet->mergeCells("{$column[$col]}1:{$column[$col+$length]}1")
                ->setCellValue("{$column[$col]}1",$t['name']);
            $col+=$length+1;
        }

        //第二行
        $sheet->setCellValue('A2','')
            ->setCellValue('B2','');
        $col=2;
        foreach($base as $i=>$t){
          foreach($t['answer'] as $key=>$value){
              $length=count($value)-1;
              $sheet->setCellValue("{$column[$col]}2",$key)
                  ->mergeCells("{$column[$col]}2:{$column[$col+$length]}2");
              $col+=$length+1;
          }
        }


        //第三行
        $sheet->setCellValue('A3','')
            ->setCellValue('B3','');

        $col=2;
        foreach($base as $t){
            foreach($t['answer'] as $key=>$value){
                if(is_array($value)){
                    foreach($value as $k=>$v){
                        $sheet->setCellValue("{$column[$col]}3",$k);
                        $col++;
                    }
                }else{
                    $sheet->setCellValue("{$column[$col]}3",'');
                    $col++;
                }
            }
        }

        $writer=new Xlsx($spreadsheet);
        $writer->save(ROOT_PATH.'test.xlsx');
    }
}
